<template>
  <div ref="chartRef" :style="{ width: width, height: height }"></div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  options: {
    type: Object,
    default: () => ({})
  },
  autoResize: {
    type: Boolean,
    default: true
  }
});

const chartRef = ref(null);
const chart = ref(null);

const initChart = () => {
  if (chartRef.value) {
    chart.value = echarts.init(chartRef.value);
    chart.value.setOption(props.options);
  }
};

const resizeChart = () => {
  if (chart.value) {
    chart.value.resize();
  }
};

watch(
  () => props.options,
  (newVal) => {
    if (chart.value) {
      chart.value.setOption(newVal);
    }
  },
  { deep: true }
);

onMounted(() => {
  initChart();
  if (props.autoResize) {
    window.addEventListener('resize', resizeChart);
  }
});

onBeforeUnmount(() => {
  if (chart.value) {
    chart.value.dispose();
  }
  if (props.autoResize) {
    window.removeEventListener('resize', resizeChart);
  }
});
</script>
